package com.cswnode.demo.service.impl;

import com.cswnode.demo.dao.EnterpriseUserDao;
import com.cswnode.demo.entity.EnterpriseUser;
import com.cswnode.demo.entity.User;
import com.cswnode.demo.enums.YesOrNoEnum;
import com.cswnode.demo.service.EnterpriseUserService;
import com.cswnode.demo.service.UserService;
import com.cswnode.demo.util.Constant;
import com.cswnode.demo.util.Utils;
import com.cswnode.demo.vo.EnterpriseUserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.List;
import java.util.Map;

/**
 * 企业用户表(EnterpriseUser)表服务实现类
 *
 * @author makejava
 * @since 2021-01-26 11:10:00
 */
@Service
public class EnterpriseUserServiceImpl implements EnterpriseUserService , Constant {
    @Autowired
    private EnterpriseUserDao enterpriseUserDao;
    @Autowired
    private UserService userService;
    /**
     * 事物
     */
    @Autowired
    private DataSourceTransactionManager transactionManager;

    /**
     * 通过ID查询单条数据
     *
     * @param entUserId 主键
     * @return 实例对象
     */
    @Override
    public EnterpriseUser queryById(Long entUserId) {
        return this.enterpriseUserDao.queryById(entUserId);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<EnterpriseUser> queryAllByLimit(int offset, int limit) {
        return this.enterpriseUserDao.queryAllByLimit(offset, limit);
    }

    @Override
    public List<EnterpriseUserVo> queryAllByVo(int offset, int limit, String userNameCn) {
        return enterpriseUserDao.queryAllByVo(offset, limit, userNameCn);
    }

    @Override
    public int selectNum(String usernameCn) {
        return enterpriseUserDao.selectNum(usernameCn);
    }

    /**
     * 新增数据
     *
     * @param enterpriseUser 实例对象
     * @return 实例对象
     */
    @Override
    public EnterpriseUser insert(EnterpriseUser enterpriseUser) {
        this.enterpriseUserDao.insert(enterpriseUser);
        return enterpriseUser;
    }

    @Override
    @Transactional
    public String insertUser(EnterpriseUserVo enterpriseUserVo) {
        User user = new User();
        EnterpriseUser enterpriseUser = new EnterpriseUser();
        BeanUtils.copyProperties(enterpriseUserVo, user);
        BeanUtils.copyProperties(enterpriseUserVo, enterpriseUser);
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setName("SomeTxName");
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            Map<String, Object> result = userService.insert(user);
            if (result.containsKey(ERROR)) {
                return (String) result.get(ERROR);
            }
            if (result.containsKey(SUCCESS)) {
                User success = (User) result.get(SUCCESS);
                enterpriseUser.setUserId(success.getUserId());
                enterpriseUser.setCreateTime(success.getCreateTime());
                enterpriseUser.setIsDelete(YesOrNoEnum.NO.getCode());
                enterpriseUser.setEntUserId(null);
                int insert = enterpriseUserDao.insert(enterpriseUser);
                if (insert > 0) {
                    return null;
                }
                transactionManager.rollback(status);
            }

        } catch (Exception e) {
            transactionManager.rollback(status);
            throw e;
        }
        return null;
    }

    /**
     * 修改数据
     *
     * @param enterpriseUserVo 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public String update(EnterpriseUserVo enterpriseUserVo) {
        User user = new User();
        EnterpriseUser enterpriseUser = new EnterpriseUser();
        BeanUtils.copyProperties(enterpriseUserVo, user);
        BeanUtils.copyProperties(enterpriseUserVo, enterpriseUser);
        int update = enterpriseUserDao.update(enterpriseUser);
        if (update == 0){
            throw new IllegalArgumentException("修改失败");
        }
        String s = userService.updateUser(user);
        if (StringUtils.isNotEmpty(s)){
            throw new IllegalArgumentException(s);
        }
        return "修改成功！";
    }

    /**
     * 通过主键删除数据
     *
     * @param entUserId 主键
     * @return 是否成功
     */
    @Override
    @Transactional
    public boolean deleteById(Long entUserId) {

        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setName("SomeTxName");
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            enterpriseUserDao.deleteById(entUserId);
            userService.deleteById(entUserId);
            return true;
        } catch (Exception e) {
            transactionManager.rollback(status);
            throw e;
        }
    }

    @Override
    public Long getEntId() {
        Long userId = Utils.getLoginUser().getUserId();
        Long entId = enterpriseUserDao.getEntId(userId);
        return entId;
    }
}